package com.huawei.aiosproj.guiagent;

import android.util.Log;

import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit; // Import TimeUnit

public class GUIAgentEngine {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    // Configure the OkHttpClient with timeouts
    private final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS) // Connection timeout
            .writeTimeout(30, TimeUnit.SECONDS)   // Write timeout
            .readTimeout(30, TimeUnit.SECONDS)    // Read timeout
            .build();
    private static final String TAG = "GUIAgentEngine";

    public void sendMultimodalRequest(String apiKey, String imageUrl) throws IOException, JSONException {
        // 1. 构建 JSON 请求体
        JSONObject contentText = new JSONObject();
        contentText.put("text", "图片主要讲了什么?");
        contentText.put("type", "text");

        JSONObject imageUrlObj = new JSONObject();
        imageUrlObj.put("url", imageUrl);

        JSONObject contentImage = new JSONObject();
        contentImage.put("image_url", imageUrlObj);
        contentImage.put("type", "image_url");

        JSONArray contents = new JSONArray();
        contents.put(contentText);
        contents.put(contentImage);

        JSONObject message = new JSONObject();
        message.put("content", contents);
        message.put("role", "user");

        JSONArray messages = new JSONArray();
        messages.put(message);

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "doubao-1-5-ui-tars-250428");
        requestBody.put("messages", messages);

        // 2. 创建 Request 对象
        Request request = new Request.Builder()
                .url("https://ark.cn-beijing.volces.com/api/v3/chat/completions")
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .post(RequestBody.create(requestBody.toString(), JSON))
                .build();

        // 3. 发送异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                // 处理请求失败
                // You might want to log more specific error messages or inform the user
                Log.e(TAG, "Request failed: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    // It's good practice to log the response code and body if possible
                    Log.e(TAG, "Unexpected code " + response + " - " + response.body().string());
                    throw new IOException("Unexpected code " + response);
                }

                // 4. 处理响应数据
                String responseData = response.body().string();
                // 解析并处理返回的JSON数据
                processResponse(responseData);
            }
        });
    }

    private void processResponse(String jsonResponse) {
        try {
            JSONObject responseObj = new JSONObject(jsonResponse);
            // 解析响应数据，例如：
            JSONArray choices = responseObj.getJSONArray("choices");
            if (choices.length() > 0) {
                JSONObject firstChoice = choices.getJSONObject(0);
                String messageContent = firstChoice.getJSONObject("message")
                        .getString("content");
                Log.e(TAG, "processResponse: " + messageContent); // Changed to Log.d for general info
            }
        } catch (JSONException e) { // Catch JSONException specifically
            Log.e(TAG, "JSON parsing error: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) { // Catch other potential exceptions
            Log.e(TAG, "Error processing response: " + e.getMessage());
            e.printStackTrace();
        }
    }
}